using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Sapphire.Linq.Framework;

namespace Sapphire.Linq.Mappers
{
    public class SPFieldLookupValueMapper : IObjectMapper
    {
        public TTo Map<TTo>(object value, object[] parameters)
        {
            var lookUpValues = new List<SPFieldLookupValue> { new SPFieldLookupValue(value.ToString()) };

            if (lookUpValues.FirstOrDefault().LookupId == 0)
                return default(TTo);

            var queryProvider = parameters.OfType<LinqQueryProvider>().First();

            var field = parameters.OfType<SPFieldLookup>().First();

            var listQuery = queryProvider.GetList<TTo>(new Guid(field.LookupList));

            var whereLambda = lookUpValues.GetByIds<TTo>();

            return listQuery.FirstOrDefault(whereLambda);
        }

        public bool IsMatch<TTo>(object value, object[] parameters)
        {
            return parameters.OfType<SPFieldLookup>().FirstOrDefault() != null;
        }
    }
}